package com.gitee.wsl.time.interval

import com.gitee.wsl.ext.base.currentTimeMillis


/**
 * TrueTime is used to solve time skew.
 *
 * @author 释慧利
 */
object TrueTime {
    private const val HEARTBEAT_OFFSET: Long = 0
    private var trueTimestamp: Long = currentTimeMillis
    private var localTimestamp = trueTimestamp

    /**
     * update time.
     *
     * @param trueTimestamp target time
     */
    fun heartbeat(trueTimestamp: Long) {
        val local: Long = currentTimeMillis
        if (trueTimestamp <= local) {
            return
        }
        TrueTime.trueTimestamp = trueTimestamp + HEARTBEAT_OFFSET
        localTimestamp = local
    }

    /**
     * get current time.
     *
     * @return current time
     */
    fun timeMillis(): Long {
        val local: Long = currentTimeMillis
        val diff = local - localTimestamp
        return trueTimestamp + diff
    }
}
